package com.cfweb.controller.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cfweb.controller.LoginHandler;
import com.cfweb.dao.AppTemplateMapper;
import com.cfweb.dao.CfEnvironmentMapper;
import com.cfweb.dao.CfServiceMapper;
import com.cfweb.dao.TemSerMapper;
import com.cfweb.domain.AppTemplate;
import com.cfweb.domain.AppTemplateExample;
import com.cfweb.domain.AppTemplateExample.Criteria;
import com.cfweb.domain.AppTemplateExternal;
import com.cfweb.domain.CfEnvironment;
import com.cfweb.domain.CfService;
import com.cfweb.domain.TemSer;
import com.cfweb.domain.TemSerExample;
import com.cfweb.util.ExtJSResponse;
import com.cfweb.util.StringUtil;

/**
 * 
 * @author (yufangjiang) Dec 2, 2014
 */
@Service
@Path("/template")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class TemplateManagement {
	/**
	 * session
	 */
	@Autowired
	private HttpSession session;
	/**
	 * 应用模板
	 */
	@Autowired
	private AppTemplateMapper atMapper;
	/**
	 * 模板服务
	 */
	@Autowired
	private TemSerMapper tsMapper;
	/**
	 * 服务
	 */
	@Autowired
	private CfServiceMapper csMapper;
	/**
	 * buildpack
	 */
	@Autowired
	private CfEnvironmentMapper ceMapper;

	/**
	 * 获取当前org，space的模板
	 * 
	 * @return
	 */
	@Path("/listall")
	@GET
	public ExtJSResponse listall() {
		List<AppTemplate> lat = null;
		AppTemplateExample atlEx = new AppTemplateExample();
		String org = (String) session.getAttribute(LoginHandler.ORG);
		String space = (String) session.getAttribute(LoginHandler.SPACE);
		if (StringUtil.isEmpty(org) && StringUtil.isEmpty(space)) {
			return ExtJSResponse.successRes();
		}
		Criteria criteria = atlEx.createCriteria();
		if (!StringUtil.isEmpty(org)) {
			criteria.andOrgEqualTo((String) org);
		}
		if (!StringUtil.isEmpty(space)) {
			criteria.andSpaceEqualTo(space);
		}
		AppTemplateExample atlEx2 = new AppTemplateExample();
		atlEx2.createCriteria().andOrgIsNull().andSpaceIsNull();
		lat = atMapper.selectByExample(atlEx2);
		lat.addAll(atMapper.selectByExample(atlEx));
		return ExtJSResponse.successResWithData(lat);
	}

	/**
	 * 获取系统模板 根据type来判断
	 * 
	 * @author add by 龙立强
	 * @return
	 */
	@Path("/listTemplateOfAdmin")
	@GET
	public ExtJSResponse listTemplateOfAdmin() {
		List<AppTemplate> lat = null;
		AppTemplateExample atlEx = new AppTemplateExample();
		atlEx.createCriteria().andTypeEqualTo(0);
		lat = atMapper.selectByExample(atlEx);
		System.out.println("-----------------");
		System.out.println(lat);
		System.out.println(lat.size());
		return ExtJSResponse.successResWithData(lat);
	}

	/**
	 * 只获取当前用户的模板 根据用户ID和type来判断
	 * 
	 * @author add by 龙立强
	 * @return
	 */
	@Path("/listTemplateOfCurrentUser")
	@GET
	public ExtJSResponse listTemplateOfCurrentUser() {
		List<AppTemplate> lat = null;
		AppTemplateExample atlEx = new AppTemplateExample();
		// String org = (String) session.getAttribute(LoginHandler.ORG);
		// String space = (String) session.getAttribute(LoginHandler.SPACE);
		String userID = (String) session.getAttribute(LoginHandler.USERID);

		// if (StringUtil.isEmpty(org) && StringUtil.isEmpty(space)) {
		// return ExtJSResponse.successRes();
		// }
		if (StringUtil.isEmpty(userID)) {
			return ExtJSResponse.successRes();
		}

		Criteria criteria = atlEx.createCriteria();

		if (!StringUtil.isEmpty(userID)) {
			criteria.andUuidEqualTo(userID);

		}

		AppTemplateExample atlEx2 = new AppTemplateExample();
		atlEx2.createCriteria().andUuidEqualTo(userID);
		lat = atMapper.selectByExample(atlEx2);
		lat.addAll(atMapper.selectByExample(atlEx));
		return ExtJSResponse.successResWithData(lat);
	}

	/**
	 * return <b>json</b> like below : {"data" : { "template":[], "appList":[],
	 * "anaList":[], "stoList":[], "othList":[], "env":{} }, "success":true }
	 * 
	 * @param tpId
	 *            (id of template）
	 * @return
	 */
	@Path("/getone")
	@GET
	public ExtJSResponse list(@QueryParam("id") int tpId) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		AppTemplate templ = atMapper.selectByPrimaryKey(tpId);
		resMap.put("template", templ);
		resMap.put("org", (String) session.getAttribute(LoginHandler.ORG));
		resMap.put("space", (String) session.getAttribute(LoginHandler.SPACE));
		TemSerExample tsEx = new TemSerExample();
		tsEx.createCriteria().andTemIdEqualTo(tpId);
		List<TemSer> tsList = tsMapper.selectByExample(tsEx);
		CfEnvironment env = ceMapper.selectByPrimaryKey(templ.getEnvId());
		resMap.put("env", env);

		List<CfService> stoList = new ArrayList<CfService>();
		List<CfService> anaList = new ArrayList<CfService>();
		List<CfService> appList = new ArrayList<CfService>();
		List<CfService> othList = new ArrayList<CfService>();

		if (tsList != null) {
			for (TemSer ts : tsList) {
				CfService ser = csMapper.selectByPrimaryKey(ts.getSerId());
				if (ser != null) {
					switch (ser.getSerType()) {
					case 1: {
						stoList.add(ser);
						break;
					}
					case 2: {
						anaList.add(ser);
						break;
					}
					case 3: {
						appList.add(ser);
						break;
					}
					default: {
						othList.add(ser);
						break;
					}
					}
				}
			}
		} // 添加服务类型的list
		resMap.put("stoList", stoList);
		resMap.put("anaList", anaList);
		resMap.put("appList", appList);
		resMap.put("othList", othList);

		return ExtJSResponse.successResWithData(resMap);
	}

	/**
	 * 通过服务的id获取该服务下的可以使用的数据库, 目前尚未完善
	 * 
	 * @param id
	 * @return
	 */
	@Path("/getStore")
	@GET
	public ExtJSResponse getStore(@QueryParam("id") int id) {
		CfService cs = null;

		return ExtJSResponse.successResWithData(cs);
	}

	/**
	 * 删除模板
	 * 
	 * @param id
	 * @return
	 */
	@Path("/delete")
	@DELETE
	public ExtJSResponse delete(@QueryParam("id") int id) {
		atMapper.deleteByPrimaryKey(id);
		TemSerExample tmEx = new TemSerExample();
		tmEx.createCriteria().andTemIdEqualTo(id);
		tsMapper.deleteByExample(tmEx);
		return ExtJSResponse.successRes();
	}

	/**
	 * create a template
	 * 
	 * @param temName
	 * @param evnId
	 * @param serviceIds
	 * @param orgName
	 * @param spaceName
	 * @param domain
	 * @param memory
	 * @param disk
	 * @param instance
	 * @return update by 龙立强 在创建模板时同时记录当前用户的uuid
	 */
	@Path("/add")
	@GET
	public ExtJSResponse createTemplate(@QueryParam("temName") final String temName,
			@QueryParam("evnId") final Integer evnId, @QueryParam("serviceIds") final String serviceIds,
			@QueryParam("orgName") final String orgName, @QueryParam("spaceName") final String spaceName,
			@QueryParam("domain") final String domain, @QueryParam("memeory") final Integer memory,
			@QueryParam("disk") final Integer disk, @QueryParam("instance") final Integer instance) {

		String userID = (String) session.getAttribute(LoginHandler.USERID);

		if (StringUtil.isEmpty(userID)) {
			// TODO 如果是空说明当前用户没有登录，要提示用户重新登录
		}

		Integer type = getUserTypeBySession();

		AppTemplate tpl = new AppTemplateExternal(temName, evnId, orgName, spaceName, domain, memory, disk, instance,
				type, userID);
		atMapper.insertSelective(tpl);
		Integer id = tpl.getId();
		if (!StringUtil.isEmpty(serviceIds)) {
			String[] serIds = serviceIds.split(",");
			for (String serId : serIds) {
				TemSer tm = new TemSer();
				tm.setSerId(Integer.valueOf(serId));
				tm.setTemId(id);
				tsMapper.insert(tm);
			}
		}
		return ExtJSResponse.successRes();

	}

	/**
	 * 修改模板
	 * 
	 * @param tpl
	 * @return
	 */
	@Path("/add")
	@PUT
	public ExtJSResponse add(AppTemplate tpl) {
		atMapper.insertSelective(tpl);
		return ExtJSResponse.successRes();

	}

	/**
	 * 编辑模板
	 * 
	 * @param id
	 * @param temName
	 * @param evnId
	 * @param serviceIds
	 * @param orgName
	 * @param spaceName
	 * @param domain
	 * @param memeory
	 * @param disk
	 * @param instance
	 * @return
	 */
	@Path("/edit")
	@GET
	public ExtJSResponse editTemplate(@QueryParam("id") final Integer id, @QueryParam("temName") final String temName,
			@QueryParam("evnId") final Integer evnId, @QueryParam("serviceIds") final String serviceIds,
			@QueryParam("orgName") final String orgName, @QueryParam("spaceName") final String spaceName,
			@QueryParam("domain") final String domain, @QueryParam("memeory") final Integer memeory,
			@QueryParam("disk") final Integer disk, @QueryParam("instance") final Integer instance) {

		String userID = (String) session.getAttribute(LoginHandler.USERID);
		Integer type = (Integer) session.getAttribute(LoginHandler.USERISADMIN);

		AppTemplate tpl = new AppTemplateExternal(id, temName, evnId, orgName, spaceName, domain, memeory, disk,
				instance, type, userID);
		tpl.setTemColor("#99d0f9");
		tpl.setTemImg("resources/img/icons/module.png");
		tpl.setType(1);
		atMapper.updateByPrimaryKey(tpl);
		TemSerExample tsEx = new TemSerExample();
		tsEx.createCriteria().andIdEqualTo(id);
		tsMapper.deleteByExample(tsEx);
		TemSerExample reTsEx = new TemSerExample();
		reTsEx.createCriteria().andTemIdEqualTo(tpl.getId());
		tsMapper.deleteByExample(reTsEx);
		if (!StringUtil.isEmpty(serviceIds)) {
			String[] serIds = serviceIds.split(",");
			for (String serId : serIds) {
				TemSer tm = new TemSer();
				tm.setSerId(Integer.valueOf(serId));
				tm.setTemId(id);
				tsMapper.insert(tm);
			}
		}

		return ExtJSResponse.successRes();

	}

	/**
	 * 验重
	 * 
	 * @param temName
	 * @param orgName
	 * @param spaceName
	 * @return
	 */
	@Path("/checkTemName")
	@GET
	public ExtJSResponse checkTemName(@QueryParam("temName") final String temName,
			@QueryParam("orgName") final String orgName, @QueryParam("spaceName") final String spaceName) {
		AppTemplateExample atlEx = new AppTemplateExample();
		atlEx.createCriteria().andTemNameEqualTo(temName).andSpaceEqualTo(spaceName).andOrgEqualTo(orgName);
		List<AppTemplate> atemlist = new ArrayList<>();
		atemlist = atMapper.selectByExample(atlEx);
		if (atemlist.size() > 0) {
			return ExtJSResponse.successResWithData(false);
		}
		return ExtJSResponse.successResWithData(true);
	}

	/***
	 * 根据session获取当前用户的type
	 * 
	 * @return
	 */
	private Integer getUserTypeBySession() {
		Integer userisadmin = (Integer) session.getAttribute(LoginHandler.USERISADMIN);
		Integer type = null;
		if (userisadmin == 1) {// 管理员
			type = 0;// type=0 是系统模板
		}

		if (userisadmin == 0) {// 普通用户
			type = 1;// type=1 是用户模板
		}
		return type;
	}

}
